﻿namespace S4sme.Web.Areas.Blog.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Mail;
    using System.Web.Mvc;

    using S4sme.Core.Configuration;
    using S4sme.Core.Services;
    using S4sme.Domain;
    using S4sme.Tasks.Blog;

    public class CommentController : Controller
    {
        private readonly CommentCudTasks commentTasks;

        public CommentController(CommentCudTasks commentTasks)
        {
            this.commentTasks = commentTasks;
        }
        
        [HttpPost]
        /* NOTE: [ValidateAntiForgeryToken] was throwing the exception: System.Web.Mvc.HttpAntiForgeryException. A required anti-forgery token was not supplied or was invalid. */
        public ActionResult Edit(Comment comment)
        {
            if (ModelState.IsValid)
            {
                comment.CreatedDate = DateTime.Now;
                comment.Ip = IpService.GetIpAddress();
                var confirmation = this.commentTasks.SaveOrUpdate(comment);

                if (confirmation.WasSuccessful)
                {
                    EmailService.SendEmail(
                    new MailAddress(Settings.EmailAddress),
                    "New Comment",
                    "S4sme blog - new comment",
                    comment.Content,
                    comment.Avatar);

                    // TempData["message"] = confirmation.Message;
                    return RedirectToAction("Message", "Notification", new { message = Resources.Resource_Blog.MsgCommentsNeedApproval, returnUrl = Url.Action("DetailsById", "Posts", new { id = comment.PostFk }) });
                }

                this.ViewData["message"] = confirmation.Message;
            }

            // we are passing validation errors manually as built-in validation is not working???
            var errors = this.ModelState.Values.SelectMany(modelState => modelState.Errors).Select(error => error.ErrorMessage).ToList();
            this.TempData["Errors"] = errors;
            return RedirectToAction("DetailsById", "Posts", new { id = comment.PostFk });
        }
    }
}
